package com.platform.boot.security.group.member;

import com.platform.boot.security.group.GroupsRepository;
import com.platform.boot.utils.BaseAutoToolsUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.relational.core.query.Query;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * @author <a href="https://github.com/vnobo">Alex bob</a>
 */
@Service
@RequiredArgsConstructor
public class GroupMembersService extends BaseAutoToolsUtil {

    private final GroupMembersRepository memberRepository;
    private final GroupsRepository groupsRepository;

    public Flux<GroupMemberOnly> search(GroupMemberRequest request, Pageable pageable) {
        return entityTemplate.select(Query.query(request.toCriteria()).with(pageable), GroupMember.class)
                .flatMap(this::serializeOnly);
    }

    public Mono<Page<GroupMemberOnly>> page(GroupMemberRequest request, Pageable pageable) {
        return search(request, pageable).collectList()
                .zipWith(entityTemplate.count(Query.query(request.toCriteria()), GroupMember.class))
                .map(tuple2 -> new PageImpl<>(tuple2.getT1(), pageable, tuple2.getT2()));
    }

    private Mono<GroupMemberOnly> serializeOnly(GroupMember groupMember) {
        return groupsRepository.findByCode(groupMember.getGroupCode())
                .map(group -> GroupMemberOnly.withGroupMember(groupMember).group(group));
    }

    public Flux<GroupMember> operate(GroupMemberRequest request) {
        return Flux.empty();
    }

    public Mono<Void> delete(Long id) {
        return this.memberRepository.deleteById(id);
    }


}